package com.spring.housing.util;
import com.spring.housing.constant.Constants;
import com.spring.housing.returnType.CommenResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public  class FileUpload {
    public static CommenResult upload(MultipartFile file ,String filePath) throws IOException {
         Map<String, Object> map = new HashMap<String, Object>();
        if(file!=null){
            String fileName= UUID.randomUUID()+"";
//            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//            ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes)requestAttributes;
         String pathName=   filePath+fileName+"_"+ Constants.LOGINSESSION+"."+file.getContentType().substring(file.getContentType().lastIndexOf("/")+1);
            map.put("fileame", file.getName());
            // 设置文件类型
            map.put("contentType", file.getContentType());
            // 设置文件大小
            map.put("fileSize", file.getSize());
            map.put("filePath",pathName);
         File save = new File(pathName);
         file.transferTo(save);
        }
        else {
            return new CommenResult(500,"文件为空!","文件上传失败!");
        }
        return new CommenResult(200,"文件上传成功!",map);
    }
}
